<?php

namespace App\Services;

use App\Common\Services\BaseService;
use App\Common\Tools\CustomException;
use App\Models\Ocean\ChannelProjectModel;
use App\Models\Ocean\OceanPromotionModel;

class ChannelPromotionService extends BaseService {
    /**
     * @param $data
     * @return array
     * @throws CustomException
     * 详情
     */
    public function read($data){
        $this->validRule($data, [
            'channel_id' => 'required|integer'
        ]);

        $channelProjectModel = new ChannelProjectModel();
        $projectIds = $channelProjectModel->where('channel_id', $data['channel_id'])->pluck('project_id')->toArray();

        $builder = new OceanPromotionModel();
        $builder = $builder
            ->whereIn('project_id', $projectIds)
            ->when(isset($data['keyword']),function ($query) use ($data){
                return $query->whereRaw("
                        (id LIKE '%{$data['keyword']}%' OR name LIKE '%{$data['keyword']}%')
                    ");
            });

        // 过滤
        if(!empty($data['filtering'])){
            $builder = $builder->filtering($data['filtering']);
        }

        $res = $builder->listPage($data['page'] ?? 1, $data['page_size'] ?? 10);

        foreach($res['list'] as $promotion){
            unset($promotion['extends']);

            $promotion->ocean_account;
            if(!empty($promotion->ocean_promotion_extends)){
                $promotion->convert_callback_strategy = $promotion->ocean_promotion_extends->convert_callback_strategy;
                $promotion->convert_callback_strategy_group = $promotion->ocean_promotion_extends->convert_callback_strategy_group;
                unset($promotion->ocean_promotion_extends);
            }else{
                $promotion->convert_callback_strategy = null;
                $promotion->convert_callback_strategy_group = null;
            }
        }

        $res['channel_id'] = $data['channel_id'];
        return $res;
    }
}
